package com.umsoft.chapter2.helper;

import com.umsoft.chapter2.util.CollectionUtil;
import com.umsoft.chapter2.util.PropsUtil;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class DatabaseHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseHelper.class);
    private static final ThreadLocal<Connection> CONNECTION_HOLDER ;
    private static final QueryRunner QUERY_RUNNER ;
    private static final BasicDataSource DATA_SOURCE;

    private static final String DRIVER;
    private static final String URL;
    private static final String USER;
    private static final String PASSWORD;
    static {
        CONNECTION_HOLDER = new ThreadLocal<>();
        QUERY_RUNNER = new QueryRunner();

        Properties props = PropsUtil.loadProps("config.properties");
        DRIVER =  PropsUtil.getString(props,"jdbc.driver");
        URL = PropsUtil.getString(props,"jdbc.url");
        USER = PropsUtil.getString(props,"jdbc.username");
        PASSWORD = PropsUtil.getString(props,"jdbc.password");

        DATA_SOURCE = new BasicDataSource();
        DATA_SOURCE.setDriverClassName(DRIVER);
        DATA_SOURCE.setUrl(URL);
        DATA_SOURCE.setUsername(USER);
        DATA_SOURCE.setPassword(PASSWORD);
    }

    public  static void executeSqlFile(String file) {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String sql ;
        try {
            while ((sql = reader.readLine()) != null) {
                DatabaseHelper.excuteUpdate(sql);
            }
        }catch (Exception e){
            LOGGER.error("execute sql file failure",e);
        }
    }

    public static  int excuteUpdate(String sql,Object... params){
        int rows = 0;
        Connection connection = getConnection();
        try {
            rows = QUERY_RUNNER.execute(connection,sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.error("excute update failure",e);
            throw new RuntimeException(e);
        }
        return rows;
    }

    public static <T> Boolean insertEntity(Class<T> entityClass,Map<String,Object> fieldMap){
        if(CollectionUtil.isEmpty(fieldMap)){
            LOGGER.error("can not insert entity: fieldMap is empty");
            return false;
        }
        String sql = "INSERT INTO "+ getTableName(entityClass);
        StringBuilder columns = new StringBuilder("(");
        StringBuilder values = new StringBuilder("(");
        StringBuilder finalColumns = columns;
        StringBuilder finalValues = values;
        fieldMap.forEach((k, v)->{
            finalColumns.append(k).append(",");
            finalValues.append("?,");
        });
        columns = columns.replace(columns.lastIndexOf(","),columns.length(),")");
        values = values.replace(values.lastIndexOf(","),values.length(),")");
        sql +=  columns + " VALUES " +values;
        Object[] params = fieldMap.values().toArray();
        return excuteUpdate(sql,params) == 1;
    }

    public static <T> Boolean updateEntity(Class<T> entityClass,Map<String,Object> fieldMap,Map<String,Object> paramMap){
        if(CollectionUtil.isEmpty(fieldMap)){
            LOGGER.error("can not update entity: fieldMap is empty");
            return false;
        }
        String sql = "UPDATE "+ getTableName(entityClass) + " SET ";
        StringBuilder columns = new StringBuilder();
        StringBuilder finalColumns = columns;
        fieldMap.forEach((k, v)->{
            finalColumns.append(k).append("=?,");

        });
        columns = new StringBuilder(columns.substring(0,columns.lastIndexOf(",")));
        StringBuilder whereParams = new StringBuilder();
        if(CollectionUtil.isNotEmpty(paramMap)){
            whereParams = new StringBuilder(" WHERE ");
            StringBuilder finalWhereParams = whereParams;
            paramMap.forEach((k, v)->{
                finalWhereParams.append(k).append("=? AND ");
            });
            whereParams = new StringBuilder(finalWhereParams.substring(0,finalWhereParams.lastIndexOf("AND")));
        }

        sql = sql + columns + whereParams;
        Object[] params = ArrayUtils.addAll( fieldMap.values().toArray(),paramMap.values().toArray());

        return excuteUpdate(sql,params) == 1;
    }

    public static <T> Boolean deleteEntity(Class<T> entityClass,Map<String,Object> paramMap){
        String sql = "DELETE FROM "+getTableName(entityClass);
        StringBuilder whereParams = new StringBuilder();
        if(CollectionUtil.isNotEmpty(paramMap)){
            whereParams = new StringBuilder(" WHERE ");
            StringBuilder finalWhereParams = whereParams;
            paramMap.forEach((k, v)->{
                finalWhereParams.append(k).append("=? AND ");
            });
            whereParams = new StringBuilder(finalWhereParams.substring(0,finalWhereParams.lastIndexOf("AND")));
        }

        sql = sql + whereParams;
        Object[] params = paramMap.values().toArray();
        return excuteUpdate(sql,params)>0;
    }

    private static <T> String getTableName(Class<T> entityClass) {
        return entityClass.getSimpleName();
    }

    public static List<Map<String,Object>> excuteQuery(String sql,Object... params){
        List<Map<String,Object>> result = new ArrayList<>();
        Connection connection = getConnection();
        try {
            result = QUERY_RUNNER.query(connection,sql,new MapListHandler(),params);
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.error("excute query failure",e);
            throw new RuntimeException(e);
        }
        return result;
    }

    public static <T> T queryEntity(Class<T> entityClass,String sql,Object ... params){
        T entity = null;
        Connection connection = getConnection();

        try {
            entity = QUERY_RUNNER.query(connection,sql,new BeanHandler<>(entityClass),params);
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.error("query entity failure",e);
            throw new RuntimeException(e);
        }

        return entity;
    }

    public static <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object ... params){
        List<T> entityList = null;
        Connection connection = getConnection();;
        try {
            entityList = QUERY_RUNNER.query(connection,sql,new BeanListHandler<T>(entityClass),params);
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.error("query entity list failure",e);
            throw new RuntimeException(e);
        }
        return entityList;
    }

    public static Connection getConnection(){
        Connection connection = CONNECTION_HOLDER.get();
        if(connection == null){
            try {
                connection = DATA_SOURCE.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
                LOGGER.error("get connection failure",e);
            }finally {
               CONNECTION_HOLDER.set(connection);
            }
        }

        return connection;
    }
}
